﻿using BLL;
using Model;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.库存管理;
using 后整理管理系统.报表窗体;
using 后整理管理系统.自定义类;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.报表窗体;
using 纺织贸易管理系统.设置窗体;

namespace 纺织贸易管理系统.选择窗体
{
    public partial class 库存报表 : Form
    {
        public string StockName { get; set; } = "";
        public List<StockTable> pingzhong { get; set; }
        private readonly List<JuanHaoTable> juanlist = new List<JuanHaoTable>();

        public 库存报表()
        {
            InitializeComponent();
            CreateGrid.Create(this.Name, gridView1);
            CreateGrid.Create(this.Name, gridView2);
            CreateGrid.Query<JuanHaoTable>(gridControl2, juanlist);
            CreateGrid.Query<StockTable>(gridControl1, pingzhong);
            gridView1.OptionsCustomization.AllowSort = true;
            CreatLeibie();
            try
            {
                cmbmaitou.Items.AddRange(Tools.获取模板.获取所有模板(PrintPath.唛头模板).ToArray());
                cmbmaitou.SelectedIndex = 0;
            }
            catch
            {
                this.ShowErrorDialog("没有找到任何唛头模板信息");
            }
        }
        private void CreatLeibie()
        {
            treeView1.Nodes.Clear();
            var lblist = Connect.CreatConnect().Query("select distinct ckmc from stocktable");
            var node = new TreeNode() { Text = "所有仓库", Name = "所有仓库" };
           for(int i=0;i<lblist.Rows.Count;i++)
            {
                node.Nodes.Add(new TreeNode() { Text = lblist.Rows[i][0].ToString (), Name = lblist.Rows[i][0].ToString() });
            }
            treeView1.Nodes.Add(node);
            treeView1.ExpandAll();
        }
        private void 品种选择_Load(object sender, EventArgs e)
        {
            uiPagination1_PageChanged(null, null, 1, txtpagesize.Text.ToInt());
        }
        private void Query()
        {
            //this.ShowWaitForm("正在查询，请等待.............");
            //string querystring = $"select count(*) from stocktable where ContractNum like '%{txthetonghao.Text }%' and " +
            //    $"pm like '%{txtpingming.Text }%' and " +
            //    $"gg like '%{txtguige.Text }%' and " +
            //    $"gh like '%{txtganghao.Text }%' and " +
            //    $"kuanhao like '%{txthuohao.Text }%' and " +
            //    $"CKMC like '%{StockName }%' and " +
            //    $"ColorNum like '%{txtsehao.Text }%' and " +
            //    $"CustomName like '%{txtkehu.Text }%' and " +
            //    $"BH like '%{txtBianhao.Text}%' and " +
            //    $"orderNum like '%{txtOrderNum.Text }%' and " +
            //    $"CKMC != '色卡仓库' and  " +
            //    $"rq between '{dateTimePicker1.Value.Date}' and '{dateTimePicker2.Value.AddDays(1).Date }' ";
            //  pingzhong = StockTableService.GetStockTablelst(x => x.ContractNum.Contains(txthetonghao.Text) && x.PM.Contains(txtpingming.Text) && x.GG.Contains(txtguige.Text) && x.GH.Contains(txtganghao.Text) && x.kuanhao.Contains(txthuohao.Text) && x.CKMC.Contains(StockName)
            //&& x.ColorNum.Contains(txtsehao.Text) && x.CustomName.Contains(txtkehu.Text) && x.BH.Contains(txtBianhao.Text) && x.orderNum.Contains(txtOrderNum.Text) && x.CKMC != "色卡仓库" && x.RQ >= dateTimePicker1.Value.Date && x.RQ <= dateTimePicker2.Value).OrderByDescending(x => x.RQ).ToList();
            //uiPagination1.TotalCount = Connect.dbcontext.Queryable<StockTable>().Where(x=>x.ContractNum.Contains(txthetonghao.Text )&&x.PM.Contains(txtpingming.Text )&&
            //x.GG.Contains(txtguige.Text )&&x.kuanhao.Contains (txthuohao.Text )&&x.CKMC==StockName&&x.ColorNum.Contains (txtsehao.Text )&&x.CustomName.Contains (txtkehu.Text)&&
            //x.BH.Contains (txtBianhao.Text )&&x.orderNum.Contains(txtOrderNum.Text)&&x.RQ>=dateTimePicker1.Value.Date &&x.RQ<=dateTimePicker2.Value.AddDays(1)).ToPageList(uiPagination1.);
            //txtCount.Text = uiPagination1.TotalCount.ToString();
            uiPagination1_PageChanged(null,null,1,txtpagesize.Text .ToInt () );
            //gridControl1.DataSource = pingzhong;
            //this.HideWaitForm();
        }
        private void 配置列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView1) { formname = this.Name, Obj = new StockTable() };
            fm.ShowDialog();
        }

        private void txtbianhao_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Query();
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            StockName = treeView1.SelectedNode.Text == "所有仓库" ? "" : treeView1.SelectedNode.Text;
            gridControl2.DataSource = null;
            Query();
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView2) { formname = this.Name, Obj = new JuanHaoTable() };
            fm.ShowDialog();
        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            加载卷();
        }
        private void 加载卷()
        {
            int id = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").TryToInt();
            var d =StockTableService.GetOneStockTable  (x=>x.ID ==id);            
            gridControl2.DataSource = new StockHelper().加载卷(d);
        }
        /// <summary>
        /// 获取选中的库存
        /// </summary>
        /// <returns></returns>
        private List<StockTable> GetSelectStocks()
        {
            List<StockTable> stocks = new List<StockTable>();
            List<StockTable> stockTables = gridControl1.DataSource as List<StockTable>;
            foreach (var index in gridView1.GetSelectedRows())
            {
                int id = gridView1.GetRowCellValue(index, "ID").TryToInt();
                stocks.Add(stockTables.First(x=>x.ID==id));
            }
            return stocks;
        }
        private void 清零选择库存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确定要把这些选中的库存清零吗？", this.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                List<StockTable> stocks = new List<StockTable>();
                List<StockTable> stockTables = gridControl1.DataSource as List<StockTable>;
                foreach (var index in SelectHelper.GetSelectList<StockTable >(gridView1 ))
                {                                   
                    stocks.Add(index);
                }
                foreach (var s in stocks)
                {
                    if (Connect.dbcontext.Queryable<JuanHaoTable>().Where(x => x.ReceiptNo == s.RKDH && x.GangHao == s.GH && x.SampleName == s.PM && x.yanse == s.YS&&x.state==0).Count() > 0)
                    {
                        Tools.ShowMessageBox.ShowErrorBox("发现库存信息\r\n入库单号：" + s.RKDH + "\r\n品名:" + s.PM + "\r\n缸号:" + s.GH + "\r\n颜色:" + s.YS + "\r\n存在未发的细码卷,请先到细码库存里面把这些细码标识为已发货状态！清零库存失败");
                        return;
                    } 
                }
                库存BLL.清零库存(stocks);
            }
            Query();
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreatLeibie();
            treeView1.SelectedNode = new TreeNode("所有仓库");
            Query();
        }

        private void 录入明细ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var fm = new 录入可发卷() { stock = StockTableService.GetOneStockTable (x => x.ID == (int)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID")) };
                fm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
                fm.ShowDialog();
            }
            else
            {
                AlterDlg.Show("没有任何库存可录入");
            }
        }

        private void 打印编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (后整理管理系统.自定义类.PrintService.CheckPrintDesignAccess())
            {
                var fm = new 打印设置窗体();
                //fm.ShowDialog();
                var juanlist = gridControl2.DataSource as DataTable;
                var moban = MaitouService.GetOneMaitou(x => x.khbh == (String)juanlist.Rows[gridView2.FocusedRowHandle]["CustomerName"]).path;
                if (!string.IsNullOrWhiteSpace(moban))
                {
                    moban = cmbmaitou.Text;
                }
                new Tools.打印唛头() { copyies = fm.copyies, PrinterName = fm.printer, userful = PrintModel.Design, moban = PrintPath.唛头模板 + moban, juan = JuanHaoTableService.GetOneJuanHaoTable(x => x.JuanHao == (string)gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "JuanHao")) }.打印();
            }
        }

        private void 保存样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView1);
        }

        private void 保存样式ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView2);
        }

        private void 删除卷ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var res = MessageBox.Show("您确定要删除选中的卷吗？", this.Name, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res == DialogResult.OK)
            {
                foreach (var i in gridView2.GetSelectedRows())
                {
                    可发卷BLL.卷删除(gridView2.GetRowCellValue(i, "JuanHao").ToString());
                }
                加载卷();
            }
        }
        private void 导出到EXCELToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportFile.导出到文件(gridControl1, "库存清单");
        }

        private void 打印预览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 打印设置窗体();
            //fm.ShowDialog();
            var moban = MaitouService.GetOneMaitou(x => x.khbh ==gridView2.GetRowCellValue (gridView2.FocusedRowHandle,"CustomerName").ToString ()).path;
            if (string.IsNullOrWhiteSpace(moban))
            {
                moban = cmbmaitou.Text;
            }
            new Tools.打印唛头() { copyies = fm.copyies, PrinterName = fm.printer, userful = PrintModel.Privew, moban = PrintPath.唛头模板 + moban, juan = JuanHaoTableService.GetOneJuanHaoTable(x => x.JuanHao == (string)gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "JuanHao")) }.打印();
        }

        private void 直接打印ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var fm = new 打印设置窗体();
            fm.ShowDialog();
            var juanlist = gridControl2.DataSource as DataTable;
            var moban = MaitouService.GetOneMaitou(x => x.khbh == (String)juanlist.Rows[gridView2.FocusedRowHandle]["CustomerName"]).path;
            if (!string.IsNullOrWhiteSpace(moban))
            {
                moban = cmbmaitou.Text;
            }
            foreach (var index in gridView2.GetSelectedRows())
            {
                new Tools.打印唛头() { copyies = fm.copyies, PrinterName = fm.printer, userful = PrintModel.Print, moban = PrintPath.唛头模板 + moban, juan = JuanHaoTableService.GetOneJuanHaoTable(x => x.JuanHao == (string)gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "JuanHao")) }.打印();
            }
        }

        private void 订单转换ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (BLL.AccessBLL.CheckAccess("订单转换"))
            {
                if (gridView1.FocusedRowHandle >= 0)
                {
                   var fm=new 订单转换() { OldOrder =StockTableService.GetOneStockTable (x=>x.ID ==(int )gridView1.GetRowCellValue(gridView1.FocusedRowHandle,"ID"))};
                    fm.ShowDialog();
                    if (treeView1.SelectedNode != null)
                    {
                        StockName = treeView1.SelectedNode.Text == "所有仓库" ? "" : treeView1.SelectedNode.Text;
                    }
                    else
                    {
                        StockName = "";
                    }
                    gridControl2.DataSource = null;
                    Query();
                }
            }
            else
            {
                ShowMessageBox.ShowErrorBox (  "您没有权限使用该功能！请让管理员给您开通");
            }
        }

        private void 查看垃圾桶ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainForm.mainform.AddMidForm(new 垃圾桶());
        }

        private void 查看超期库存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 超期库存();
            fm.ShowDialog();
        }

        private void uiPagination1_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            this.ShowWaitForm("正在查询，请等待.............");
            //string querystring = $"select * from stocktable where ContractNum like '%{txthetonghao.Text }%' and " +
            //    $"pm like '%{txtpingming.Text }%' and " +
            //    $"gg like '%{txtguige.Text }%' and " +
            //    $"gh like '%{txtganghao.Text }%' and " +
            //    $"kuanhao like '%{txthuohao.Text }%' and " +
            //    $"CKMC like '%{StockName }%' and " +
            //    $"ColorNum like '%{txtsehao.Text }%' and " +
            //    $"CustomName like '%{txtkehu.Text }%' and " +
            //    $"BH like '%{txtBianhao.Text}%' and " +
            //    $"orderNum like '%{txtOrderNum.Text }%' and " +
            //    $"CKMC != '色卡仓库' and  " +
            //    $"rq between '{dateTimePicker1.Value.Date}' and '{dateTimePicker2.Value.AddDays(1).Date }' order by rq desc offset ({pageIndex  }-1)*{count} row fetch next {count} row only";
            //  pingzhong = StockTableService.GetStockTablelst(x => x.ContractNum.Contains(txthetonghao.Text) && x.PM.Contains(txtpingming.Text) && x.GG.Contains(txtguige.Text) && x.GH.Contains(txtganghao.Text) && x.kuanhao.Contains(txthuohao.Text) && x.CKMC.Contains(StockName)
            //&& x.ColorNum.Contains(txtsehao.Text) && x.CustomName.Contains(txtkehu.Text) && x.BH.Contains(txtBianhao.Text) && x.orderNum.Contains(txtOrderNum.Text) && x.CKMC != "色卡仓库" && x.RQ >= dateTimePicker1.Value.Date && x.RQ <= dateTimePicker2.Value).OrderByDescending(x => x.RQ).ToList();
            // gridControl1.DataSource = Connect.CreatConnect().Query (querystring );
            //gridControl1.DataSource = pingzhong;
            int totalpage=0, totalnum=0;
          gridControl1.DataSource=   Connect.dbcontext.Queryable<StockTable>().Where(x => x.ContractNum.Contains(txthetonghao.Text) && x.PM.Contains(txtpingming.Text) &&
           x.GG.Contains(txtguige.Text) && x.kuanhao.Contains(txthuohao.Text) && x.CKMC.Contains ( StockName) && x.YS.Contains(txtsehao.Text) && x.CustomName.Contains(txtkehu.Text) &&
         x.GH.Contains (txtganghao.Text )&&  x.BH.Contains(txtBianhao.Text) && x.orderNum.Contains(txtOrderNum.Text) ).ToPageList(pageIndex,count,ref totalnum,ref totalpage);
            uiPagination1.TotalCount = totalnum;
            txtCount.Text = totalnum.ToString();
            this.HideWaitForm();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if(this.ShowAskDialog ("是否复检选中的库存？\r\n确定后将清空相对应的所有的已打卷记录"))
            {
                foreach (var index in gridView1.GetSelectedRows())
                {
                    var id = gridView1.GetRowCellValue(index, "ID");
                    var juans = Connect.dbcontext.Queryable<JuanHaoTable>().Where(x => x.Ckmc == id.ToString()).ToList();
                    juans.ForEach(x => x.state = 1);
                    try
                    {
                        Connect.dbcontext.BeginTran();
                        Connect.dbcontext.Updateable(juans).ExecuteCommand();
                        Connect.dbcontext.Insertable<DeleteLog>(new DeleteLog() { date=DateTime.Now , useID =Tools.CurrentUser.user .YHBH, Reason ="点击复检库存！缸号为:" + gridView1.GetRowCellValue(index, "GH") }).ExecuteCommand();
                        Connect.dbcontext.CommitTran();
                    }
                    catch(Exception ex)
                    {
                        Connect.dbcontext.RollbackTran();
                        Tools.ShowMessageBox.ShowErrorBox(ex.Message);
                    }
                }
                MessageBox.Show("复检完成");
            }
        }

        private void 已完成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var index in gridView1.GetSelectedRows())
            {
                var id = gridView1.GetRowCellValue(index, "ID").TryToInt ();
                StockTableService.UpdateStockTable(x => x.IsCheckDone == "已结束", x => x.ID == id);
            }
            Query();
        }

        private void 设定唛头ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (AccessBLL.CheckAccess("重设唛头"))
            {
                if (Tools.ShowMessageBox.ShowAskBox("您确定要把选中的这些布料设定成当前的唛头模板吗？") == DialogResult.Yes)
                {
                    var stocks = GetSelectStocks();
                    stocks.ForEach(x => x.ShippingMark = cmbmaitou.Text);
                    try
                    {
                        Connect.dbcontext.CommitTran();
                        Connect.dbcontext.Updateable(stocks).ExecuteCommand();
                        Connect.dbcontext.CommitTran();
                        Tools.ShowMessageBox.ShowInfoBox("重新设定完成！");
                    }
                    catch (Exception ex)
                    {
                        Connect.dbcontext.RollbackTran();
                        Tools.ShowMessageBox.ShowErrorBox("重新设置唛头的时候发送了错误！" + ex.Message);
                    }
                }
            }
            else
            {
                Tools.ShowMessageBox.ShowErrorBox("你没有权限重新设置唛头！请与管理员联系！");
            }
        }

        private void 检验完毕ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectStock = SelectHelper.GetSelectList<StockTable>(gridView1).FirstOrDefault();
            if (selectStock != null)
            {
                var fm = new 检验完毕()
                {
                    stock = selectStock
                };
                fm.ShowDialog();
                if (!fm.IsCancel) {
                    selectStock.JS = fm.Juanshu;
                    selectStock.MS = fm.Mishu;
                }
                try
                {
                    Connect.dbcontext.BeginTran();
                    StockTableService.UpdateStockTable(selectStock);
                    Connect.dbcontext.CommitTran();
                }
                catch (Exception ex)
                {
                    Connect.dbcontext.RollbackTran();
                    this.ShowErrorDialog("检验完毕的是否发生了错误！" + ex.Message);
                }
                Query();
            }
            else
            {
                this.ShowErrorDialog("没有任务布料被选中");
            }
        }

        private void 添加信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectStock = SelectHelper.GetSelectList<StockTable>(gridView1);
            var fm = new 添加信息(selectStock);
            fm.ShowDialog();
            Query();
        }
    }
}
